#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <winsock2.h>
#include <pthread.h>
#include "../include/client.h"

#define LOCAL_IP      "127.0.0.1"
#define LOCAL_PORT    ((uint16_t)502)

#define debug(...)                                     \
do                             \
{                              \
printf(__VA_ARGS__);       \
fflush(stdout);            \
}while(0)


SOCKET *startTcpClient() {
    int ret = 0;
    WSADATA ws;
    SOCKET sock = INVALID_SOCKET;
    sockaddr_in server;
    int nrecv = 0;
    char buf[100];

    if (WSAStartup(MAKEWORD(2, 2), &ws) != 0) {
        debug("WSAStartup failed\n");
        ret = -1;
        return nullptr;
    }

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock == INVALID_SOCKET) {
        debug("socket failed\n");
        ret = -2;
        closesocket(sock);
        return nullptr;
    }

    server.sin_family = AF_INET;
    server.sin_addr.S_un.S_addr = inet_addr(LOCAL_IP);
    server.sin_port = htons(LOCAL_PORT);

    if (connect(sock, (struct sockaddr *) &server, sizeof(struct sockaddr_in)) < 0) {
        debug("connect failed (%i)\n", WSAGetLastError());
        ret = -3;
        closesocket(sock);
        return nullptr;
    }

    // memset(buf, 'A', sizeof(buf));

    // while (1) {
    //     if (send(sock, buf, sizeof(buf), 0) < 0) {
    //         debug("send failed\n");
    //         break;
    //     }
    //
    //
    //     if ((nrecv = recv(sock, buf, sizeof(buf), 0)) <= 0) {
    //         debug("recv failed\n");
    //         break;
    //     }
    //
    //     if (strncmp(buf, "quit", 4) == 0) {
    //         debug("quit\n");
    //         break;
    //     }
    // }

    return  sock != INVALID_SOCKET ? &sock : nullptr ;
}

int32_t tcp_read(SOCKET sock, uint8_t *buf, uint16_t count, int32_t timeout_ms) {
    // 直接使用传入的缓冲区，不需要创建新的缓冲区
    if (buf == nullptr || count == 0) {
        return -1;
    }
    
    // 使用recv函数读取数据
    const auto res = recv(sock, (char*)buf, count, 0);
    
    if (res == SOCKET_ERROR) {
        std::cerr << "[ERROR] TCP read failed with error: " << WSAGetLastError() << std::endl;
        return -1;
    }
    
    return res;
}

int32_t tcp_write(SOCKET sock, const uint8_t *buf, uint16_t count, int32_t timeout_ms) {
    // 直接使用传入的缓冲区，不需要创建新的缓冲区
    if (buf == nullptr || count == 0) {
        return -1;
    }
    
    // 使用send函数发送数据
    const auto res = send(sock, (char*)buf, count, 0);
    
    if (res == SOCKET_ERROR) {
        std::cerr << "[ERROR] TCP write failed with error: " << WSAGetLastError() << std::endl;
        return -1;
    }
    
    return res;
}
